<?php if(!defined('OCTOMS')){header('HTTP/1.1 403');die('{"error":"forbidden"}');}
/*
 * @package       OctoMS.com
 * @subpackage    DesignJotter
 * @link          http://DesignJotter.com
 * @copyright     Copyright 2012, Valentino-Jivko Radosavlevici (http://valentino.radosavlevici.com)
 * @license       GPL v3.0 (http://www.gnu.org/licenses/gpl-3.0.txt)
 * 
 * Redistributions of files must retain the above copyright notice.
 * 
 * @since         OctoMS 0.0.1
 */
	
	/*
	 * Main model
	 * 
	 * @link http://octoms.com/doc/main_m
	 * 
	 * @package OctoMS
	 * @subpackage WP-OctoMS
	 * @version 0.1
	 * 
	 * @author Valentino-Jivko Radosavlevici
	 */
	class main_m extends octoms
	{	
		/**
		 * Step 2 checking model
		 * 
		 */
		function step2_check()
		{
			// Prepare the result
			$result = array();
			
			// Check for the PHP version
			$result['php'] = array(
				'status'=>((version_compare(PHP_VERSION, '5.2.0') >= 0) ? 'done' : 'error'),
				'title'=>'PHP version',
				'desc'=>'Your server must run PHP version 5.2+.'
			);
			
			// Check for the GD library
			$result['gd'] = array(
				'status'=> (in_array('gd', get_loaded_extensions()) ? 'done' : 'error'),
				'title'=>'PHP GD library',
				'desc'=>'In order to resize images and perform other 
				graphic modifications, the PHP GD library is necessary.'
			);
			
			// Check the permalink structure
			$result['permalink'] = array(
				'status'=> (strlen(get_option('permalink_structure'))>0?'done':'error'),
				'title'=>'Permalink structure',
				'desc'=>'In order for the portfolio and the contact pages to work correctly 
				you must set a permalink structure, <b>any other than</b> the default.<br/>
				Please <a href="'.str_replace('/admin.php','/options-permalink.php',ADMINROOT).'" target="_blank">select a permalink structure 
				different from the default</a> now.'
			);
			
			// Check for the "Projects" category
			$result['projects'] = array(
				'status'=>(term_exists( 'Projects' , 'category' ) ? 'done' : 'pending'),
				'title'=>'The "Projects" category',
				'desc'=>'Every post written within the "projects" category 
				is listed on the "Recent Projects" page and via the "Recent 
				projects" widget.<br/> Remember to upload a featured image 
				for each project!'
			);
			
			// Check for the "Home" page
			if (WP_FRONT_PAGE == 'static')
			{
				$done = false;
				if (0 != $id = $this->settings->_prefix()->get('page_on_front'))
				{
					$p = get_post($id,ARRAY_A);
					if (is_array($p) && $p['post_status'] == 'publish')
					{
						$done = true;
					}
				}
				$result['home'] = array(
					'status'=>($done?'done':'pending'),
					'title'=>'The homepage',
					'desc'=>'You have full control over your homepage. This 
					instructs WordPress to use the "home" page as your website\'s 
					front page.'
				);
				$this->settings->_prefix(true);
			}
			
			// All done
			return $result;
		}// end function step2_check()
		
		/**
		 * Save step 2
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function step2_save()
		{
			// Automatically advance
			$advance = true;
			
			// Create the projects category
			if ( !term_exists( 'Projects' , 'category' ) )
			{
				wp_insert_category(array(
					'cat_name' => 'Projects', 
					'category_description' => 'Our projects', 
					'category_nicename' => 'projects2', 
					'category_parent' => ''
				));
				
				// Behold the changes
				$advance = false;
			}
			
			if(strlen(get_option('permalink_structure'))==0)
			{
				$advance = false;
			}
			
			// Add the front page
			if (WP_FRONT_PAGE == 'static')
			{
				$done = false;
				if (0 != $id = $this->settings->_prefix()->get('page_on_front'))
				{
					$p = get_post($id,ARRAY_A);
					if (is_array($p) && $p['post_status'] == 'publish')
					{
						$done = true;
					}
				}
				if(!$done)
				{
					// Get the "home" content
					$file = APP_ROOT.DS.'stages'.DS.'install'.DS.'home.txt';
					
					// Valid file?
					if (file_exists($file))
					{
						$content = file_get_contents($file);
					}
					else 
					{
						$content = 'Hello world!';
					}
					
					// Create the Home page
					$post = array(
						'post_title' => 'Home',
						'post_content' => $content,
						'post_status' => 'publish',
						'post_author' => 1,
						'post_type' => 'page'
					);
					
					// Insert the post
					if(0 == $id = @wp_insert_post($post))
					{
						$this->template->_api('Post creation failed.','warning');
					}
					else 
					{
						// Set the page_on_front
						$this->settings->set('show_on_front','page');
						$this->settings->set('page_on_front',$id);
					}
					
					// Moving on
					$advance = false;
				}
				$this->settings->_prefix(true);
			}
			
			// All done
			$this->template->_api('Basic configuration set successfully!');
			
			// All good?
			return $advance;
			
		}// end function step2_save()
		
		/**
		 * Step 3 check
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function step3_check()
		{
			// Prepare the result
			$result = array();
			
			// Is installed
			$i = $this->settings->get();
			$i = (bool)($i != null && count($i)>1);
			
			// Check for the options set
			$result['options'] = array(
				'status'=>($i?'done':'pending'),
				'title'=>'Dummy content',
				'desc'=>'It\'s so much easier to learn by example! This will 
				load some default values for your <b>'.WP_OCTOMS_TITLE.'</b> theme.'
			);
			
			// Send the result
			return $result;
			
		}// end function step3_check()
		
		/**
		 * Step 3 save
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function step3_save()
		{
			// Move to the next step?
			$advance = true;
			
			// Change the HTACCESS file
			if(file_exists(ROOT.DS.'.htaccess'))
			{
				global $htaccessRoot;
				$htaccessRoot = preg_replace('%(.*?/)wp-admin.*%i', '$1', $_SERVER['PHP_SELF']).'wp-content/themes/'.ADMINSLUG.'/';
				
				// Get the file
				$file = file_get_contents(ROOT.DS.'.htaccess');
				
				// Replace the RewriteBase rule
				$file = preg_replace_callback(
					'/(#Godaddy Accounts#)([^\e]*?)(\s+RewriteCond)/i', 
					create_function(
						'$m',
						'global $htaccessRoot; 
						return $m[1].
							"\n\tRewriteBase ".
							$htaccessRoot.
							$m[3];'
					),
					$file
				);
				
				// Rewrite the .htaccess
				$fh = fopen(ROOT.DS.'.htaccess', 'w');
				fwrite($fh, $file);
				fclose($fh);
			}
			
			// Installed?
			$i = $this->settings->get();
			$i = (bool)($i != null && count($i)>1);
			
			// Install dummy content
			if (!$i)
			{
				// Install default data
				$this->settings->install();
				
				// Add the other files
				$dir = APP_ROOT.DS.'stages'.DS.'install';
				
				// Get all the files in the directory
				if (is_dir($dir))
				{
					if (FALSE !== $files = scandir($dir))
					{
						foreach ($files AS $file)
						{
							if (is_file($dir.DS.$file) && false !== strpos($file, '.txt') && $file != 'home.txt')
							{
								// Get the post name
								$post = substr($file, 0, strrpos($file, '.'));
								
								// Prepare the insert settings
								$insertSettings = array(
									'post_title' => ucfirst($post),
									'post_content' => file_get_contents($dir.DS.$file),
									'post_status' => 'publish',
									'post_author' => 1,
									'post_type' => 'page'
								);
								
								// Any post with this slug already?
								if (null !== $p = get_page_by_path($post))
								{
									$insertSettings['ID'] = $p->ID;
								}
								
								// Create or update the page
								@wp_insert_post($insertSettings);
							}
						}
					}
				}
				
				// All done
				$this->template->_api('Dummy content installed successfully!');
				
				// Don't go to the next step yet
				$advance = false;
			}
			else 
			{
				$this->template->_api('Your theme already has some options set.','info');
			}
			
			return $advance;
		}// end function step3_save()
		
		/**
		 * Step 4. Get the tips
		 * 
		 * @example 
		 * 
		 * @param 
		 * @return 
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function tips()
		{
			// Get the request object
			$this->_('request',OMS_CL);
			
			// Get the data
			$this->request->load(
				'http://www.octoms.com/wp-api/tips/'.
				strtolower(WP_OCTOMS_TITLE).
				'/'.
				WP_OCTOMS_VERSION
			);
			
			// Try to decode it
			if (null !== $data = @json_decode($this->request->body)) 
			{
				$data = object_to_array($data);
				if ($data['status'] == 'success')
				{
					// All done
					$this->template->_api('Tips received successfully!');
					
					// The text allows for shortcodes
					$data['data'] = $this->tips_shortcode($data['data']);
					
					// Return the data
					return $data;
				}
				else 
				{
					if(isset($data['data'][0]))
					{
						$this->template->_api('An error occured: "'.strval($data['data'][0]).'".',false);
						return array('data'=>'Please try again later.');
					}
					else 
					{
						$this->template->_api('Invalid server language.',false);
						return array('data'=>'Please try again later.');
					}
				}
			}
			else
			{
				$this->template->_api('Invalid server response.',false);
				return array('data'=>'Please try again later.');
			}
			
		}// end function tips()
		
		/**
		 * Tips shortcodes
		 * @param string $str
		 * @return string
		 */
		function tips_shortcode($str=null)
		{
			// Recursive call
			if (is_array($str))
			{
				foreach ($str AS $key => $value)
				{
					$str[$key] = $this->tips_shortcode($value);
				}
				return $str;
			}
			
			// Clean the string
			if (!is_string($str)) return '';
			
			// Replace the brackets
			return @preg_replace_callback(
				'/\{([^}]+)\}/i', 
				array(
					$this,
					'tips_shortcode_helper'
				), 
				$str
			);
		}// end function tips_shortcode
		
		/**
		 * Tips shortcode helper
		 * 
		 * @param array $m - Matches
		 * @author Valentino-Jivko Radosavlevici
		 */
		function tips_shortcode_helper($m)
		{
			// Get the value
			$value = $m[1];
			
			// Return a constant?
			if (0 === strpos($value,'c_')) 
			{
				$constant = strtoupper(preg_replace('%^c_(.*)$%i', '$1', $value));
				if (strlen($constant)>0 &&  defined($constant))
				{
					return constant($constant);
				}
			}
			
			// Return the baseurl?
			if (0 === strpos($value, 'baseurl'))
			{
				$exp = explode('>', $value);
				if (isset($exp[1]))
				{
					return baseurl($exp[1]);
				}
			}
			
			// User e-mail?
			if (0 === strpos($value,'user_email'))
			{
				global $user_email;
				return $user_email;
			}
			
			// Anchor
			if (0 === strpos($value, 'a>'))
			{
				$exp = explode('>', $value);
				if (isset($exp[1]))
				{
					if (false === strpos($exp[1], '//'))
					{
						$exp[1] = baseurl($exp[1]);
					}
					return a((isset($exp[2])?$exp[2]:$exp[1]),$exp[1],array('target'=>'_blank'));
				}
			}
			
			// Image
			if (0 === strpos($value, 'img>'))
			{
				$exp = explode('>', $value);
				if (isset($exp[1]))
				{
					$img = tag(
						'img',
						array(
							'src' => $exp[1]
						),
						null,
						true
					);
					
					if (isset($exp[2]))
					{
						if (false === strpos($exp[2], '//'))
						{
							$exp[2] = baseurl($exp[2]);
						}
						return a($img,$exp[2],array('target'=>'_blank'));
					}
					else 
					{
						return $img;
					}
				}
			}
			
			// Nothing good
			return '';
			
		}// end function tips_shortcode_helper()
		
		/**
		 * CSS marks
		 * 
		 * @param string $css_file
		 * @return array/null/false; Array if css marks found, null if none found, false on error
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function css_marks($css_file=null)
		{
			// The css file is mandatory
			if (is_null($css_file))
			{
				$css_file = ROOT.DS.'style-global.css';
			}
			
			// Try to load it
			if (file_exists($css_file))
			{
				$subject = file_get_contents($css_file);
			}
			else 
			{
				return false;
			}
			
			// Get all marked colors
			preg_match_all('%#([a-f0-9]{3,6})(?=.*/\*\*\*/)%i', $subject, $r, PREG_PATTERN_ORDER);
			$result = array();
			if (count($r)>0)
			{
				// Go through each color
				foreach (array_map('strtolower',array_unique($r[1])) AS $color)
				{
					// Get all CSS rules for these colors
					if (preg_match_all('%(.*?)\{([^\e}]*#'.$color.'[^a-f0-9]*?/\*\*\*/[^}]*)}%i', $subject, $m))
					{
						if (is_array($m[1]) && count($m[1])>0)
						{
							foreach ($m[1] AS $_k => $k)
							{
								// Get the keys
								foreach (explode("\n", trim($m[2][$_k])) AS $value)
								{
									// Matched our color?
									if (!empty($value) && false !== strpos($value, '/***/'))
									{
										if (preg_match('/([a-z0-9\-]*)\s*?:[^#]*#([a-f0-9]{3,6})/i', $value, $m2)) 
										{
											$result[trim($k)][trim($m2[1])] = strtoupper($m2[2]);
										}
									}
								}
							}
						}
					}	
				}
			}

			// All done
			return count($result)>0?$result:null;
			
		}// end function css_marks()
		
		/**
		 * Update CSS
		 * 
		 * @param string $css_file
		 * @return array/null/false; Array if css marks found, null if none found, false on error
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function css_update($css_file=NULL)
		{
			// The css file is mandatory
			if (is_null($css_file))
			{
				$css_file = ROOT.DS.'style-global.css';
			}
			
			// Try to load it
			if (file_exists($css_file))
			{
				$subject = file_get_contents($css_file);
			}
			else 
			{
				$this->template->_api('Invalid CSS file "'.$css_file.'".',false);
				return false;
			}

			// Set the update array
			$update = array();
				
			// Parse the POST
			foreach ($this->input->post('colors') AS $k => $item)
			{
				// Get the name
				if (isset($item['_name_']))
				{
					$name = preg_quote(trim(htmlspecialchars_decode($item['_name_'],ENT_QUOTES),'{'));
					unset($item['_name_']);
					if (strlen($name)==0) continue;
				}
				else 
				{
					continue;
				}
				
				// Replace the values
				foreach ($item AS $rule => $color)
				{
					// Remove unwanted characters
					$color = strtoupper(preg_replace('%[^a-f0-9]%i', '', $color));
					
					// Set the size
					if (strlen($color)>0)
					{
						// Smaller than the norm?
						if (strlen($color)<6)
						{
							// Repeat the string
							$color = str_pad($color, 6, $color);
						}
						elseif (strlen($color)>6)
						{
							// Trim the string
							$color = substr($color,0,6);
						}
						
						// Set the update form array
						$update['colors['.$k.']['.$rule.']'] = $color;

						// Perform the replacement
						$result = @preg_replace(
							'%((?<=\n|\})'.$name.'\s*\{[^}]*[\s;/]+'.trim($rule).'\s*:[^#]*?#)([a-z0-9]{3,6})%i',
							'${1}'.$color,
							$subject
						);

						// Valid result?
						if (null !== $result)
						{
							$subject = $result;
						}
					}
				}
			}
			
			// Save the content
			if(false !== $fh = @fopen($css_file, 'w'))
			{
				fwrite($fh,$subject,strlen($subject));
				fclose($fh);
				
				// All done
				$this->template
					->_api('CSS file updated successfully.')
					->_api(array('update'))
					->_api_cnt($update);
			}
			else 
			{
				// Could not open
				$this->template->_api('Could not open "'.$css_file.'".',false);
			}
		}// end function css_update()
		
		/**
		 * Categories get
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function categories_get()
		{
			// Get the defined user categories
			$cats = (array)get_categories(array('hide_empty'=>0));
			
			// Any result?
			if (count($cats)>0) 
			{
				// Prepare the result
				$result = array();
				
				// Go through each category
				foreach($cats AS $c)
				{
					// Convert to an array
					$c = object_to_array($c);
					
					// Get the settings
					$s = $this->settings->get('categories');
					if (is_null($s)) $s = array();
					
					// Get the saved data
					$result[$c['slug']] = array(
						'name' => $c['name'],
						'desc' => $c['category_description'],
						'posts' => $c['category_count'],
						'color' => @isset($s[$c['slug']]['color'])?$s[$c['slug']]['color']:0,
						'type' => @isset($s[$c['slug']]['type'])?$s[$c['slug']]['type']:0
					);
				}
				
				// All done
				return $result;
			}
			else
			{
				return null;
			}
		
		}// end function categories_get()
		
		/**
		 * Categories update
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function categories_update()
		{		
			// Parse the user input
			if (!is_null($cats = $this->categories_get()))
			{
				// Get the settings
				$s = $this->settings->get('categories');
				if (is_null($s)) $s = array();
					
				// Parse the categories
				foreach (array_keys($cats) AS $category)
				{
					$data = $this->input->post($category);
					$s[$category] = array(
						'color' => isset($data['color'])?$data['color']:0,
						'type' => isset($data['type'])?$data['type']:0
					);
				}
				
				// Update the data
				$this->settings->set('categories',$s);
				
				// All done
				$this->template->_api('Categories updated successfully!');
			}
			else 
			{
				$this->template->_api('No categories to reference.',false);
			}
			
		}// end function categories_update()
		
		/**
		 * Get the categories available icons' colors and types
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function categories_icons($iconWidth=null,$iconHeight=null,$name=null)
		{
			// Format the standard icon width and height
			$iconWidth  = (is_null($iconWidth))?60:intval($iconWidth);
			$iconHeight = (is_null($iconHeight))?60:intval($iconHeight);
			
			// Format the name
			$name = (is_null($name))?'symbols.png':strval($name);
			
			// If the image exists
			if (file_exists($f = ROOT.DS.'img'.DS.$name)) 
			{
				// Load the image library
				$this->_('image');
			
				// Load the image to get its properties
				$img = $this->image->load($f,true);
				
				// Prepare the result
				$result = array();
				
				// Colors
				$result['colors'] = $img['w']/$iconWidth;
				
				// Types
				$result['types'] = $img['h']/$iconHeight;
				
				// All done
				return $result;
			}
			else 
			{
				return $f;
			}
			
		}// end function categories_icons()
		
		/**
		 * Front update
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function index_update()
		{
			$this->settings->set('body_class',$this->input->post('body_class','all'));
			$this->template->_api(
				sprintf(
					'Body pattern updated successfully (%s)!',
					$this->input->post('body_class','all')
				)
			);
			
		}// end function front_update()
		
		/**
		 * Front upload
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function index_upload($name,$width,$height)
		{
			try
			{
				// Get the file
				$file = $this->input->file($name);
				if (strlen($file['name'])>0)
				{
					// Upload the (temporary) image
					$this->input->upload(
						$name,
						'front',
						'header-temp.png',
						array(
							'image/png',
							'image/gif',
							'image/jpeg'
						),
						null,
						null,
						true
					);
	
					// Load the image library
					$this->_('image',OMS_CL);
					
					// Get the old image location
					$old = ROOT.DS.'upload'.DS.'front'.DS.'header.png';
					
					// Get the new image location
					$new = ROOT.DS.'upload'.DS.'front'.DS.'header-temp.png';
					
					// Get the image
					$img = $this->image->load($new,true);
					
					// Ratio
					$ratio = $width/$height;
					$new_ratio = $img['w']/$img['h'];
					$bad_ratio = ($ratio>1 && $new_ratio<=1) || ($ratio<=1 && $new_ratio>1);
					
					// The width and height must be large
					if (($img['w'] < $width || $img['h'] < $height) || $bad_ratio)
					{
						// Remove it and set an error message
						unlink($new);
						$this->template->_api('Your image must be at least '.$width.'x'.$height.' pixels (at this approximate W/H ratio)!',false);
					}
					else 
					{
						// Remove the old file
						unlink($old);
						
						// Rename the new file
						@rename($new, $old);
						
						// Success!
						$this->template->_api('Header changed successfully!');
					}
				}
				else 
				{
					$this->template->_api('Invalid filename.',false);
				}
			}
			catch (Exception $e)
			{
				$this->template->_api($e->getMessage(),false);
			}
			
			// Reload
			$this->template->_r('_main/front_page');
			
		}// end function front_upload()
		
		/**
		 * Front - add image
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function front_add_image($name)
		{
			// Get the file
			$file = $this->input->file($name);
			
			// Upload?
			if (strlen($file['name'])>0) 
			{
				// Get the file name
				$save = md5(microtime(true));
				
				// Get the settings
				$s = $this->settings->get('slider');
				
				// This needs to be an array
				if (is_null($s)) $s = array();
				
				// Get the weights
				$weights = array();
				foreach ($s AS $_s)
				{
					if (isset($_s['weight']))
					{
						$weights[] = $_s['weight'];
					} 
				}
				
				// Invalid weight?
				if (in_array($this->input->post('weight'), $weights))
				{
					$this->template
						->_api('Weight already set. Fix and try again.',false);
				}
				else 
				{
					try 
					{
						// Upload the file
						$this->input->upload(
							$name,
							'front',
							$save.'.png',
							array(
								'image/png',
								'image/gif',
								'image/jpeg'
							),
							null,
							null,
							true
						);
						
						// Load the image library
						$this->_('image',OMS_CL);
						
						// Get the image
						$img = $this->image->load(ROOT.DS.'upload'.DS.'front'.DS.$save.'.png',true);
						
						// Thumbnail (200width)
						$thumb = $this->image->resize($img['r'],'width=200');
						$this->image->save($thumb,'png',ROOT.DS.'upload'.DS.'front'.DS.$save.'-thumb.png');
						
						// Large (920x330)
						$img = $this->image->resize($img['r'],'920','330');
						$this->image->save($img,'png',ROOT.DS.'upload'.DS.'front'.DS.$save.'.png');
						
						// Append the item
						$s[$save] = array(
							'desc'=>$this->input->post('desc'),
							'weight'=>$this->input->post('weight')
						);
						
						// Save the settings
						$this->settings->set('slider',$s);
						
						// All done
						$this->template->_api('File uploaded successfully!');
					}
					catch (Exception $e)
					{
						// Something went wrong
						$this->template->_api('Upload failed. '.$e->getMessage(),false);
					}
				}
			}
			else 
			{
				$this->template->_api('Nothing to upload','info');
			}
			
			// Reload
			$this->template->_r('_main/slider');
			
		}// end function front_add_image()
		
		/**
		 * Front image list
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function front_list()
		{
			// Get the Settings
			$s = $this->settings->get('slider');

			// This needs to be an array
			if (!is_null($s))
			{
				// Prepare the result
				$result = array();
				
				// Process the array
				foreach ($s AS $k=>$v)
				{
					$result[$v['weight']] = array(
						// Get the thumbnail version
						'thumb'=>WEBROOT.'/upload/front/'.$k.'-thumb.png',
						'full'=>WEBROOT.'/upload/front/'.$k.'.png',
						'desc'=>$v['desc'],
						'weight'=>$v['weight'],
						'id'=>$k
					);
				}
				
				// Sort the result
				ksort($result);
				
				// All done
				return $result;
			}
			else 
			{
				return null;
			}
			
		}// end function front_list()
		
		/**
		 * Front updat
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function front_update()
		{
			// Get the settings
			$s = $this->settings->get('slider');
			if (is_null($s)) $s = array();
			
			// Get the weights
			$weigths = array();
			
			// Sent the effect procedure
			if ($this->input->post('effect'))
			{
				$effects = array();
				foreach ($this->input->post('effect') AS $effect => $set)
				{
					$effects[$effect] = ($set === 'true');
				}
				$this->settings->set('slider_effects',$effects);
				$this->template->_api('Effects saved successfully!');
				return;
			}
			
			// Parse all the post keys
			foreach ($_POST AS $k => $v)
			{
				// Get the information
				if (false !== strpos($k,'-'))
				{
					// Get the parts
					$exp = explode('-', $k);
					
					// Get the field and id
					$field = $exp[0];
					$id = $exp[1];
					
					// The id must exist
					if (isset($s[$id]) && is_array($s[$id]))
					{
						// Manage the weight
						if ($field=='weight')
						{
							if (in_array($v, $weigths))
							{
								$this->template
									->_api('Weight already set. Fix and try again.',false)
									->_api(array('mark'))
									->_api_cnt(array('id'=>'weight-'.$id));
								return;
							}
							else 
							{
								$weigths[] = $v;
							}
						}
						
						// Don't save the "delete" parameter
						if ($field == 'delete')
						{
							if ($v == 'true') 
							{
								unset($s[$id]);
								$this->_front_remove($id);
							}
						}
						else 
						{
							// Save the field
							$s[$id][$field] = $v;
						}
					}
				}
			}
			
			// Save the information
			$this->settings->set('slider',$s);
			
			// All done
			$this->template
				->_api('Slider saved successfully.')
				->_api(array('refresh'));
			
		}// end function front_update()
		
		/**
		 * Front effects
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function front_effects($set=false)
		{
			$effects = $this->settings->get('slider_effects');
			$result = array();
			if (!is_null($effects))
			{
				foreach ($effects AS $effect=>$set)
				{
					if ($set)
					{
						$result[] = $effect;
					}
				}
				return $result;
			}
			else 
			{
				return array();
			}
			
		}// end function front_effects()
		
		/**
		 * Front remove image helper
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function _front_remove($id)
		{
			// Set the files path
			$path = ROOT.DS.'upload'.DS.'front'.DS;
			
			// Set the files
			$files = array(
				$path.$id.'.png',
				$path.$id.'-thumb.png'
			);
			
			// Remove the files
			foreach ($files AS $f)
			{
				if (file_exists($f))
				{
					unlink($f);
				}
			}
		}// end function _front_remove()
		
		/**
		 * Facebook get saved data
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function facebook_get()
		{
			return (array)$this->settings->get('facebook');
			
		}// end function facebook_get()
		
		/**
		 * Facebook save posted data
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function facebook_update()
		{
			// Set the allowed keys
			$allowed = array('appId');
			
			// Prepare the result
			$result = $this->facebook_get();
			
			// Get the post values
			foreach($allowed AS $key)
			{
				$result[$key] = $this->input->post($key);
			}
			
			// Save the value
			$this->settings->set('facebook',$result);
			
			// All done
			$this->template->_api('Facebook information saved successfully!');
			
		}// end function facebook_update()
		
		/**
		 * Update the identity page
		 * 
		 * @example 
		 * 
		 * @param 
		 * @return 
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function identity_update()
		{
			// Go through all the accounts
			$data = array();
			foreach($this->identity_accounts() AS $k => $v)
			{
				if (null !== $this->input->post($k))
				{
					$data[$k] = $this->input->post($k,'all');
				}
			}
			
			// Set the data
			$this->settings->set('identity',$data);
			
			// All done?
			$this->template
				->_api('Website identity information saved.')
				->_api(array('update'))
				->_api_cnt($data);
			
		}// end function identity_update()
		
		/**
		 * Identity reset
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function identity_reset()
		{
			// Reset the identity
			$this->settings->reset('identity');
			
			// All done
			$this->template
				->_api('Identity information reset.')
				->_api(array('update'))
				->_api_cnt($this->identity_read());
			
		}// end function identity_reset()
		
		/**
		 * List available social acounts
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function identity_accounts()
		{
			return array(
				'facebook'=>'http://facebook.com/%s',
				'twitter'=>'http://twitter.com/%s',
				'linkedin'=>'http://linkedin.com/in/%s',
				'myspace'=>'http://myspace.com/%s',
				'blogger'=>'http://blogger.com/profile/%s',
				'delicious'=>'http://delicious.com/stacks/%s',
				'youtube'=>'http://youtube.com/user/%s',
				'yahoo'=>'http://profile.yahoo.com/%s',
				'phone'=>''
			);
		}// end function identity_accounts()
		
		/**
		 * Read the site's identity
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function identity_read()
		{
			// Prepare the result
			$result = array();
			
			// Get the information saved
			$data = $this->settings->get('identity');
			
			// This must be an array
			if (is_null($data)) $data = array();
			
			// Go through all the accounts
			foreach ($this->identity_accounts() AS $k => $v)
			{
				$result[$k] = isset($data[$k])?$data[$k]:null;
			}
			
			// All done
			return $result;
			
		}// end function identity_read()
		
		/**
		 * Upload a logo
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function logo_upload($name)
		{
			try 
			{
				// Save the headline
				$this->settings->set('headline',$this->input->post('headline','all'));
				
				// Save the logo text
				$this->settings->set('logo_text',$this->input->post('logo_text','all'));
				
				// Save the copyright notice
				$this->settings->set('copyright',$this->input->post('copyright'));
				
				// Save the welcome message
				$this->settings->set('welcome',$this->input->post('welcome'));
				
				// Save the front text
				$this->settings->set('front_text',$this->input->post('front_text'));
				
				// Get the file
				$file = $this->input->file($name);
				if (strlen($file['name'])>0)
				{
					// Upload the image
					$this->input->upload(
						$name,
						'front',
						'logo.png',
						array(
							'image/png',
							'image/gif',
							'image/jpeg'
						),
						null,
						null,
						true
					);
	
					// Load the image library
					$this->_('image',OMS_CL);
					
					// Get the image
					$img = $this->image->load(ROOT.DS.'upload'.DS.'front'.DS.'logo.png',true);
					
					// Resize it
					if ($img['h']>30)
					{
						// Resize the image to a height of 30 pixels
						$img = $this->image->resize($img['r'],'height=30');
						
						// Save the image
						$this->image->save($img,'png',ROOT.DS.'upload'.DS.'front'.DS.'logo.png');
					}
					
					// All done
					$this->template->_api('Headline, logo text and logo updated successfully.');
				}
				else 
				{
					$this->template->_api('Headline and logo text updated successfully.');
				}
				
				// All done
				$this->template
					->_api(array('update'))
					->_api_cnt(array('headline'=>$this->input->post('headline','all')));
			}
			catch (Exception $e)
			{
				// Some error occured
				$this->template->_api('Headline and logo text saved successfully. '.$e->getMessage(),'warning');
			}
			
			// Reload
			$this->template->_r('_main/identity');
		}// end function logo_upload()
		
	}// end class main_m
	
	
/* End Of File <main.inc> */